package boot

import (
	"flag"
	"os"
	"time"
	"uap/common"
	"uap/controller"
	localCache "uap/pkg/localcache"
	"uap/pkg/logger"
	"uap/pkg/sqlite"
)

func init() {
	logger.Init()

	common.LocalCache = localCache.NewCache()
	common.ScanStatusCache = localCache.NewCache()
	common.CodeCache = localCache.NewCache()

	sqlite.InitSqlite()
	initDBTables()

	flag.StringVar(&common.Username, "username", "admin", "login username")
	flag.StringVar(&common.Password, "password", "konyun@2023", "login password")
	flag.StringVar(&common.Port, "port", "9999", "http listen on")
	flag.Parse()
	if v := os.Getenv("IPT_WEB_USERNAME"); len(v) > 0 {
		common.Username = v
	}
	if v := os.Getenv("IPT_WEB_PASSWORD"); len(v) > 0 {
		common.Password = v
	}
	if v := os.Getenv("IPT_WEB_PORT"); len(v) > 0 {
		common.Port = v
	}

	logger.Info("================================================")
	logger.Infof(">>>WEB服务启动成功<<<")
	logger.Infof("Web--url : http://0.0.0.0:%s", common.Port)
	logger.Infof("username : %s", common.Username)
	logger.Infof("password : %s", common.Password)
	logger.Info("================================================")

	common.Db.Table("tb_user").Create(
		&controller.TbUser{
			Username:   common.Username,
			Password:   common.Password,
			Nickname:   common.Username,
			CreateDate: time.Now().Format("2006-01-02 15:04:05"),
		})
}

func initDBTables() {
	common.Db.Table("tb_user").AutoMigrate(&controller.TbUser{})
	common.Db.Table("tb_app").AutoMigrate(&controller.TbApp{})
	common.Db.Table("tb_user_auth").AutoMigrate(&controller.TbUserAuth{})

	// common.Db.AutoMigrate(controller.TbGrant{})
	// common.Db.AutoMigrate(&controller.User{})
	// common.Db.AutoMigrate(&controller.Cmdlog{})

	// date := time.Now().Format("2006-01-02 15:04:05")
	// common.Db.Create(&controller.Cmdlog{Ip: "12.1.1.1", Username: "admin", Cmd: "iptables -L", Status: 1, Date: date})
	// controller.LogTest()
}
